'use strict';
/**
 * Created by FreezeSoul on 2015/10/16.
 */
define([
        'angular',
        'app/modules/dataset/define'
    ],
    function (angular) {
        angular.module('ad.dataset')
            .factory("adDataSetService", ['$http', '$q', '_', 'adRequest', function ($http, $q, _, adRequest) {

                function getPage(current, size, search) {
                    var deferred = $q.defer();
                    var url = adConfig.baseServiceUrl + 'dataset/dataset/search';
                    adRequest(url, {
                        criteria: search, pageIndex: current, pageSize: size
                    }).success(function (data, status, headers, config) {
                        deferred.resolve(data);
                    }).error(function (data, status, headers, config) {
                        deferred.reject(status);
                    });
                    return deferred.promise;
                }

                function addDataSet(item) {
                    var deferred = $q.defer();
                    var url = adConfig.baseServiceUrl + 'dataset/dataset/add';
                    adRequest(url, {
                        datasetId: item.dataset_id,
                        datasetName: item.dataset_name,
                        datasetCode: item.dataset_code,
                        datasetData: item.dataset_data,
                        schemaId: item.schema_id
                    }).success(function (data, status, headers, config) {
                        deferred.resolve(data);
                    }).error(function (data, status, headers, config) {
                        deferred.reject(status);
                    });
                    return deferred.promise;
                }

                function updateDataSet(item) {
                    var deferred = $q.defer();
                    var url = adConfig.baseServiceUrl + 'dataset/dataset/update';
                    adRequest(url, {
                        datasetId: item.dataset_id,
                        datasetName: item.dataset_name,
                        datasetCode: item.dataset_code,
                        datasetData: item.dataset_data,
                        schemaId: item.schema_id
                    }).success(function (data, status, headers, config) {
                        deferred.resolve(data);
                    }).error(function (data, status, headers, config) {
                        deferred.reject(status);
                    });
                    return deferred.promise;
                }


                function loadDatasetBySchema(schemaId) {
                    var deferred = $q.defer();
                    var url = adConfig.baseServiceUrl + 'dataset/dataset/getlist';
                    adRequest(url, {
                        schemaId: schemaId
                    }).success(function (data, status, headers, config) {
                        deferred.resolve(data);
                    }).error(function (data, status, headers, config) {
                        deferred.reject(status);
                    });
                    return deferred.promise;
                }


                function getDatasets() {
                    var deferred = $q.defer();
                    var url = adConfig.baseServiceUrl + 'dataset/dataset/get';
                    adRequest(url, {}).success(function (data, status, headers, config) {
                        deferred.resolve(data);
                    }).error(function (data, status, headers, config) {
                        deferred.reject(status);
                    });
                    return deferred.promise;
                }


                function removeDatasets(items) {
                    var datasetIds = _.map(items, function (item) {
                        return item.dataset_id;
                    });
                    var deferred = $q.defer();
                    var url = adConfig.baseServiceUrl + 'dataset/dataset/delete';
                    adRequest(url, {
                        datasetIds: angular.toJson(datasetIds)
                    }).success(function (data, status, headers, config) {
                        deferred.resolve(data);
                    }).error(function (data, status, headers, config) {
                        deferred.reject(status);
                    });
                    return deferred.promise;
                }


                function loadDataSetById(datasetId) {
                    var deferred = $q.defer();
                    var url = adConfig.baseServiceUrl + 'dataset/dataset/load';
                    adRequest(url, {
                        datasetId: datasetId
                    }).success(function (data, status, headers, config) {
                        deferred.resolve(data);
                    }).error(function (data, status, headers, config) {
                        deferred.reject(status);
                    });
                    return deferred.promise;
                }


                function loadDataSetByCode(datasetCode) {
                    var deferred = $q.defer();
                    var url = adConfig.baseServiceUrl + 'dataset/dataset/load';
                    adRequest(url, {
                        datasetCode: datasetCode
                    }).success(function (data, status, headers, config) {
                        deferred.resolve(data);
                    }).error(function (data, status, headers, config) {
                        deferred.reject(status);
                    });
                    return deferred.promise;
                }


                function loadExcelData(datasetCode) {
                    var deferred = $q.defer();
                    var url = adConfig.baseServiceUrl + 'common/excel/load';
                    adRequest(url, {
                        datasetCode: datasetCode
                    }).success(function (data, status, headers, config) {
                        deferred.resolve(data);
                    }).error(function (data, status, headers, config) {
                        deferred.reject(status);
                    });
                    return deferred.promise;
                }


                function updateExcelData(datasetCode, datasetGrid) {
                    var deferred = $q.defer();
                    var url = adConfig.baseServiceUrl + 'common/excel/update';
                    adRequest(url, {
                        datasetCode: datasetCode,
                        datasetGrid: angular.toJson(datasetGrid)
                    }).success(function (data, status, headers, config) {
                        deferred.resolve(data);
                    }).error(function (data, status, headers, config) {
                        deferred.reject(status);
                    });
                    return deferred.promise;
                }

                function checkDataSetCode(id, code) {
                    var deferred = $q.defer();
                    var url = adConfig.baseServiceUrl + 'dataset/dataset/check';
                    adRequest(url, {
                        datasetId: id,
                        datasetCode: code
                    }).success(function (data, status, headers, config) {
                        deferred.resolve(data);
                    }).error(function (data, status, headers, config) {
                        deferred.reject(status);
                    });
                    return deferred.promise;
                }

                function patternParams(str) {
                    var paramPattern = /\${([^\s${}]+)}/ig;//查找参数
                    var result = str.match(paramPattern);
                    return result == null ? [] : _.filter(_.uniq(_.map(result, function (r) {
                        return r.substring(2, r.length - 1);
                    })), function (p) {
                        return p != 'USER_ID' && p != 'ROLE_ID' && p != 'ROLE_LIST';
                    });
                }

                function mergeData(targetArray, sourceArray, compare, modify, defalut) {
                    if (!targetArray) return;
                    _.each(sourceArray, function (item_source) {
                        var exist = _.find(targetArray, function (item_target) {
                            return compare(item_target, item_source);
                        });
                        if (exist) {
                            modify(exist, item_source)
                        } else {
                            targetArray.push(defalut(item_source));
                        }
                    });

                    for (var i = targetArray.length - 1; i >= 0; i--) {
                        var item_target = targetArray[i];
                        var exist = _.find(sourceArray, function (item_source) {
                            return compare(item_target, item_source);
                        });

                        if (!exist) {
                            var index = targetArray.indexOf(item_target);
                            if (index > -1)
                                targetArray.splice(index, 1);
                        }
                    }
                }


                function filterSqlString(sql) {
                    var sqlStr = sql;
                    var blackList = ["alter", "begin", "create", "cursor",
                        "declare", "delete", "drop", "exec",
                        "execute", "fetch", "insert", "kill", "open",
                        "sys", "sysobjects", "syscolumns",
                        "table", "update"];
                    var blackList2 = ["--", ";", "/*", "*/", "@@", "@",];
                    _.each(blackList, function (key) {
                        sqlStr = sqlStr.replace(new RegExp("\\b" + key + "\\b", "i"), '');
                    });
                    _.each(blackList2, function (key) {
                        sqlStr = sqlStr.replace(key, '');
                    });
                    return sqlStr;
                }


                return {
                    getPage: getPage,
                    addDataSet: addDataSet,
                    updateDataSet: updateDataSet,
                    loadDataSetById: loadDataSetById,
                    loadDataSetByCode: loadDataSetByCode,
                    loadDatasetBySchema: loadDatasetBySchema,
                    getDatasets: getDatasets,
                    removeDatasets: removeDatasets,
                    checkDataSetCode: checkDataSetCode,
                    patternParams: patternParams,
                    mergeData: mergeData,
                    filterSqlString: filterSqlString,
                    loadExcelData: loadExcelData,
                    updateExcelData: updateExcelData
                };
            }]);
    });